<?php

namespace App\Admin\Forms\Customer;

use App\Enums\ReceptionType;
use App\Models\Reception;
use App\Models\User;
use App\Services\SaleService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class ReceptionAllocateForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     * @return JsonResponse
     */
    public function handle(array $input): JsonResponse
    {

        if (Reception::query()->where('user_id', $input['sale_user_id'])->doesntExist()) {
            return $this
                ->response()
                ->error(trans('接待人员数据异常，请刷新重试'));
        }
        app(SaleService::class)->receptionAllocate(false, $this->payload['id'], $input['sale_user_id']);
        return $this
            ->response()
            ->success(trans('admin.processed_successfully'))
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('sale_user_id', '销售部')
            ->options(
                User::query()->whereIn('id',
                    Reception::query()
                        ->where('status', true)
                        ->where('type', ReceptionType::SALE)
                        ->pluck('user_id')
                )->pluck('name', 'id'));
        $this->confirm('确定分配吗？', '此操作会将当前客户分配到销售部？');
    }

}
